package com.api.zszsj2.util;

import com.alibaba.fastjson.JSONObject;
import com.api.doc.detail.util.DocDownloadCheckUtil;
import com.api.hrm.service.HrmResourceBaseService;
import com.api.hrm.service.HrmResourceWorkService;
import com.api.hrm.util.ServiceUtil;
import com.api.zszsj.yzy.util.LogTool;
import com.api.zszsj2.LZL.meeting.service.impl.CsMeetingServiceImpl;
import com.engine.common.biz.SimpleBizLogger;
import com.engine.common.constant.BizLogOperateAuditType;
import com.engine.common.constant.BizLogOperateType;
import com.engine.common.constant.BizLogSmallType4Hrm;
import com.engine.common.constant.BizLogType;
import com.engine.common.entity.BizLogContext;
import com.engine.common.service.impl.HrmCommonServiceImpl;
import com.engine.common.util.LogUtil;
import com.engine.common.util.ParamUtil;
import com.engine.cube.biz.qs.ModeCreateBiz;
import com.engine.hrm.entity.RuleCodeType;
import com.engine.hrm.util.CodeRuleManager;
import com.engine.hrm.util.HrmWeakPasswordUtil;
import com.engine.hrm.util.face.HrmFaceCheckManager;
import com.engine.hrm.util.face.ValidateFieldManager;
import com.engine.hrm.util.face.bean.CheckItemBean;
import com.finance.toolkit.StringUtil;
import com.oscar.jdbc.Array;
import ln.LN;
import org.apache.commons.lang3.StringUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.file.FileUpload;
import weaver.file.Prop;
import weaver.general.PasswordUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.common.DbFunctionUtil;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.companyvirtual.DepartmentVirtualComInfo;
import weaver.hrm.finance.SalaryManager;
import weaver.hrm.passwordprotection.manager.HrmResourceManager;
import weaver.hrm.privacy.PrivacyComInfo;
import weaver.hrm.privacy.UserPrivacyComInfo;
import weaver.hrm.resource.CustomFieldTreeManager;
import weaver.hrm.resource.ResourceComInfo;
import weaver.hrm.settings.ChgPasswdReminder;
import weaver.hrm.settings.RemindSettings;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.hrm.HrmServiceManager;
import weaver.license.PluginUserCheck;
import weaver.rsa.security.RSA;
import weaver.rtx.OrganisationCom;
import weaver.rtx.OrganisationComRunnable;
import weaver.system.SysRemindWorkflow;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class HrmCommon {
    private static char separator = Util.getSeparator();
    private static String today = DateUtil.getCurrentDate();
    public static final LogTool log = new LogTool("/log/dev/zszsj2/HrmCommon", false);
    /**
     * 获得所有下级分部ID
     * @param subId
     * @return
     */
    public static String getAllChildSubBySubId(String subId){
        String str = "";
        try{
            if(subId.equals("0")){
                return str;
            }
            str = SubCompanyComInfo.getSubCompanyTreeStr(subId);
        }catch(Exception e){
            log.writeLog("Class:HrmCommon, getAllChildSubBySubId Exception:"+ e.getMessage());
        }
        return str;
    }
    /**
     * 获得所有下级部门ID
     * @param depId
     * @return
     */
    public static String getAllChildDeptByDepId(String depId){
        String str = "";
        try{
            if(depId.equals("0")){
                return str;
            }
            SubCompanyComInfo SubCompanyComInfo = new SubCompanyComInfo();
            str = SubCompanyComInfo.getDepartmentTreeStr(depId);
        }catch(Exception e){
            log.writeLog("Class:HrmCommon, getAllChildDeptByDepId Exception:"+ e.getMessage());
        }
        return str;
    }
    /**
     * 获得单位的所有下级部门ID
     * @param subCompanyId
     * @return
     */
    public static String getAllChildDeptBySubcompayId(String subCompanyId){
        String str = "";
        try{
            if(subCompanyId.equals("0")){
                return str;
            }
            RecordSet rs = new RecordSet();
            rs.executeQuery("SELECT id, departmentname FROM HrmDepartment WHERE subcompanyid1="+subCompanyId + " AND (canceled IS NULL OR canceled<>1)");
            while(rs.next()){
                String id = Util.null2String(rs.getString("id"));
                if(id.isEmpty())
                    continue;
                if(str.isEmpty()){
                    str += id;
                }else {
                    str += ","+id;
                }
            }
        }catch(Exception e){
            log.writeLog("Class:HrmCommon, getAllChildDeptBySubcompayId Exception:"+ e.getMessage());
        }
        return str;
    }

    /**
     * 检查单位列表中的单位是否都存在
     * @param subcompanylist
     * @param splitChar
     * @return
     */
    public static ApiResult checkSubCompanyListStr(String subcompanylist,String splitChar){
        ApiResult result = new ApiResult();
        if(splitChar.isEmpty())
            splitChar = ";";

        String[] companyNames;
        if(!splitChar.equals(";")){
            companyNames = subcompanylist.split(splitChar);
        }else {
            subcompanylist = subcompanylist.replace("；", ";");
            companyNames = subcompanylist.split(";");
        }
        ArrayList findList = new ArrayList();//找到该名称单位
        ArrayList unfindList = new ArrayList();//没有找到该名称单位
        ArrayList duplicateList = new ArrayList();//单位id重复
        ArrayList validateIDs = new ArrayList();//有效的单位id列表
        HashMap<String,String> IDmapName = new HashMap<String,String>();
        for(int c=0; c<companyNames.length; c++){
            if(companyNames[c].isEmpty())
                continue;

            String companyName = companyNames[c];
            int comID = getSubcompanyByName(companyName,0);
            if(comID==-1){
                unfindList.add(companyName);
            }else{
                if(findList.indexOf(companyName)>-1){
                    duplicateList.add(companyName);
                    if(validateIDs.indexOf(comID)>-1){
                        validateIDs.remove(validateIDs.indexOf(comID));
                    }
                    if(!((String)IDmapName.get(comID+"")).isEmpty()){
                        IDmapName.remove(comID+"");
                    }
                }else{
                    findList.add(companyName);
                    validateIDs.add(comID);
                    IDmapName.put(comID+"",companyName);
                }
            }
        }

        String validListId = "";
        for(int v=0; v<validateIDs.size(); v++){
            if(validListId.isEmpty()){
                validListId = validateIDs.get(v).toString();
            }else{
                validListId += ","+validateIDs.get(v).toString();
            }
        }

        String unfindListStr = "";
        for(int u=0; u<unfindList.size(); u++){
            if(unfindListStr.isEmpty()){
                unfindListStr = "【"+unfindList.get(u).toString()+"】";
            }else{
                unfindListStr += ","+"【"+unfindList.get(u).toString()+"】";
            }
        }
        if(!unfindListStr.isEmpty()){
            unfindListStr = "以下单位没找到："+unfindListStr+"！请检查！";
        }

        String duplicateListStr = "";
        for(int d=0; d<duplicateList.size(); d++){
            if(duplicateListStr.isEmpty()){
                duplicateListStr = "【"+duplicateList.get(d).toString()+"】";
            }else{
                duplicateListStr += ","+"【"+duplicateList.get(d).toString()+"】";
            }
        }
        if(!duplicateListStr.isEmpty()){
            duplicateListStr = "以下单位名称存在重复："+duplicateListStr+"！请排查重复后重试！";
        }

        result.setStatus("success");
        result.putData("validListId",validListId);
        result.putData("specialObj",IDmapName);
        String errMsg = "";
        if(!duplicateListStr.isEmpty())
            errMsg = duplicateListStr;
        if(!unfindListStr.isEmpty()) {
            if(errMsg.isEmpty())
                errMsg = unfindListStr;
            else
                errMsg = errMsg+"\n"+unfindListStr;
        }
        if(!errMsg.isEmpty()){
            result.setStatus("failed");
            result.setMessage(errMsg);
        }
        return result;
    }

    /**
     * 根据名称获取分部
     * @param name 分部
     * @param pid  上级分部id
     * @return
     */
    public static int getSubcompanyByName(String name,int pid) {
        int companyid = -1;
        RecordSet rs = new RecordSet();
        String sql="";
        if(pid==0){
            sql = "select id from HrmSubCompany where subcompanyname='"+ name + "' and (canceled<1 OR canceled IS null)";
        }else{
            sql = "select id from HrmSubCompany where subcompanyname='"+ name + "' and supsubcomid="+pid+" and (canceled<1 OR canceled IS null)";
        }
        rs.executeSql(sql);
        if(rs.next()){
            companyid = Util.getIntValue(rs.getString("id"),-1);
        }
        return companyid;
    }


    /**
     * 根据手机号和姓名查找用户是否存在，不考虑账号状态
     * @param mobile
     * @param name
     * @return
     */
    public static boolean checkUserExistByInfoMobileAndName(String mobile, String name){
        if("".equals(mobile) && "".equals(name)){
            return false;
        }

        String sql = "select * from hrmresource where (accounttype=0 or accounttype is null)";
        if(!"".equals(mobile)){
            sql += " and mobile='"+mobile+"' ";
        }if(!"".equals(name)){
            sql += " and lastname='"+name+"' ";
        }
        RecordSet rs = new RecordSet();
        rs.executeSql(sql);
        if(rs.next()){
            return true;
        }
        return false;
    }

    /**
     * 通过姓名和手机号，查找唯一用户
     * @param mobile
     * @param name
     * @param activeUserOnly    是否只查询有效用户
     * @return
     */
    public static Map<String, String> getUniqueUserIdByInfoMobileAndName(String mobile, String name, boolean activeUserOnly){
        Map<String, String> returnData = new HashMap();
        returnData.put("success","0");
        returnData.put("message","");
        returnData.put("userid",null);
        if("".equals(mobile) || "".equals(name)){
            returnData.put("message","查询条件有误");
            return returnData;
        }

        String sql = "select * from hrmresource where (accounttype=0 or accounttype is null) and mobile=? and lastname=? ";
        if(activeUserOnly){
            sql += " and status in (0,1,2,3)";
        }

        RecordSet rs = new RecordSet();
        rs.executeQuery(sql,mobile,name);
        int count =0;
        String userID = null;
        while(rs.next()){
            count++;
            if(count>1)
                break;
            userID = Util.null2String(rs.getString("id"));
        }
        if(count>1){
            returnData.put("message","账号模糊，不能指定唯一用户");
        }else{
            returnData.put("success","1");
            returnData.put("userid",userID);
        }
        return returnData;
    }

    /**
     * 通过政务认证ID（统一身份认证/粤政易），查找唯一用户
     * @param mobile
     * @param name
     * @param activeUserOnly    是否只查询有效用户
     * @return
     */
    public static Map<String, String> getUniqueUserIdByZwrzId(String zwrzId){
        Map<String, String> returnData = new HashMap();
        returnData.put("success","0");
        returnData.put("message","");
        returnData.put("userid",null);
        if("".equals(zwrzId)){
            returnData.put("message","查询条件有误");
            return returnData;
        }

        try {
            String sql = "SELECT * from Cus_FieldData where scope='HrmCustomFieldByInfoType' and scopeid='-1' AND (field0=? or field3=?)";
            RecordSet rs = new RecordSet();
            rs.executeQuery(sql, zwrzId, zwrzId);
            int count = 0;
            String userID = null;
            while (rs.next()) {
                count++;
                if (count > 1)
                    break;
                userID = Util.null2String(rs.getString("id"));
            }
            if (count > 1) {
                returnData.put("message", "账号模糊，不能指定唯一用户");
            } else {
                //再次认证是否有这个UID
                ResourceComInfo rci = new ResourceComInfo();
                String loginid = rci.getLoginID(userID);
                if(loginid!=null && loginid.length()>0){
                    returnData.put("success","1");
                    returnData.put("userid", userID);
                }else{
                    returnData.put("message", "账号无效");
                }
            }
        }catch (Exception e){
            returnData.put("message","查询遇到Exception:"+e.getMessage());
        }
        return returnData;
    }

    /**
     * 通过接口创建普通用户（主账号，普通角色普通权限）
     * @param userObj
     * @return
     */
    public static Map<String, Object> addSimpleUser(JSONObject userObj){
        Map<String, Object> retData = new HashMap<String, Object>();
        try {
            //使用系统管理员作为操作人
            User user = new User();
            String operUserid = "36905";//username='系统自动创建'
            ResourceComInfo rci = new ResourceComInfo();
            user.setUid(Integer.valueOf(operUserid));
            user.setLoginid(rci.getLoginID("" + operUserid));
            user.setLogintype("1");
            user.setFirstname(rci.getFirstname("" + operUserid));
            user.setLastname(rci.getLastname("" + operUserid));
            user.setSex(rci.getSexs("" + operUserid));
            user.setLanguage(Util.getIntValue(rci.getSystemLanguage("" + operUserid), 7));
            user.setTelephone(rci.getTelephone("" + operUserid));
            user.setMobile(rci.getMobile("" + operUserid));
            user.setEmail(rci.getEmail("" + operUserid));
            user.setLocationid(rci.getLocationid("" + operUserid));
            user.setResourcetype(rci.getResourcetype("" + operUserid));
            String jobTitle = rci.getJobTitle("" + operUserid);
            if("".equals(jobTitle) || "0".equals(jobTitle))
                jobTitle = "686";//默认 工作人员/工作人员/工作人员
            user.setJobtitle(jobTitle);
            user.setJoblevel(rci.getJoblevel("" + operUserid));
            user.setSeclevel(rci.getSeclevel("" + operUserid));
            user.setUserDepartment(Util.getIntValue(rci.getDepartmentID("" + operUserid)));
            user.setUserSubCompany1(Util.getIntValue(rci.getSubCompanyID("" + operUserid)));
            user.setManagerid(rci.getManagerID("" + operUserid));
            user.setAssistantid(rci.getAssistantID("" + operUserid));
            user.setAccount(rci.getAccount("" + operUserid));

            RecordSet rs = new RecordSet();
            String sql = "";
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            String loginid = Util.null2String(userObj.get("loginid"));
            String accounttype = "0";

            /*
            LN LN = new LN();
            int ckHrmnum = LN.CkHrmnum();
            if (ckHrmnum < 0){
                retData.put("success", "0");
                retData.put("message", 	SystemEnv.getHtmlLabelName(84760, 7));
                return retData;
            }
            */
            if (!loginid.equals("") && "0".equals(accounttype)) {
                sql = "select count(1) from hrmresourceallview where loginid='" + loginid + "' ";
                rs.executeSql(sql);
                if (rs.next()) {
                    if (rs.getInt(1) > 0) {
                        retData.put("success", "0");
                        retData.put("message", SystemEnv.getHtmlLabelName(15094, 7));
                        return retData;
                    }
                }
            }

            String departmentid = Util.null2String(userObj.get("departmentid"));
            String subcompanyid = departmentComInfo.getSubcompanyid1(departmentid);
            if (!loginid.equals("") && !subcompanyid.equals("0") && new HrmResourceManager().noMore(subcompanyid)) {
                retData.put("status", "-1");
                retData.put("message", SystemEnv.getHtmlLabelName(81926, 7));
                return retData;
            }

            ResourceComInfo ResourceComInfo = new ResourceComInfo();
            HrmResourceBaseService HrmResourceBaseService = new HrmResourceBaseService();
            Map<String, String> result = addResourceBase(userObj, user);
            log.writeLog("sub function addResourceBase result:"+result);
            String addResourceBaseCode = result.get("status") ;
            if("-1".equals(addResourceBaseCode) || "0".equals(addResourceBaseCode)){
                retData.put("success", "0");
                retData.put("message", result.get("message"));
                return retData;
            }

            int id = Util.getIntValue(result.get("id"));
            retData.put("hrmId",id);

            String password = Util.null2String(userObj.get("password"));
            ChgPasswdReminder reminder = new ChgPasswdReminder();
            RemindSettings settings = reminder.getRemindSettings();
            log.writeLog("process log 01...");
            //判断是否开启了【启用初始密码】
            String defaultPasswordEnable = Util.null2String(settings.getDefaultPasswordEnable());
            //【初始密码】
            String defaultPassword = Util.null2String(settings.getDefaultPassword());
            //如果管理员设置的密码为空。并且开启了【启用初始密码】，且初始密码不为空，则默认取初始密码作为密码
            if (password.equals("") && defaultPasswordEnable.equals("1") && !defaultPassword.equals("")) {
                password = defaultPassword;
            }
            log.writeLog("process log 02...");
//            //判断是否开启了【禁止弱密码保存】
//            String weakPasswordDisable = Util.null2s(settings.getWeakPasswordDisable(), "0");
//            if (weakPasswordDisable.equals("1")) {
//                if (password.equals("")) {//密码为空的情况
//                } else {
//                    //判断是否为弱密码
//                    HrmWeakPasswordUtil hrmWeakPasswordUtil = new HrmWeakPasswordUtil();
//                    if (hrmWeakPasswordUtil.isWeakPsd(password)) {
//                        retmap.put("status", "-1");
//                        retmap.put("message", SystemEnv.getHtmlLabelName(515420, user.getLanguage()));
//                        return JSONObject.toJSONString(retmap);
//                    }
//                }
//            }

            int seclevel = Util.getIntValue((String)userObj.get("seclevel"), 0);
            if (id > 0) {//保存系统信息
                log.writeLog("process log 03-01...");
                SimpleBizLogger logger = new SimpleBizLogger();
                BizLogContext bizLogContext = new BizLogContext();
                bizLogContext.setLogType(BizLogType.HRM);//模块类型
                bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD);//所属大类型
                bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD_SYSTEM);//当前小类型
                bizLogContext.setOperateType(BizLogOperateType.ADD);
                bizLogContext.setOperateAuditType(BizLogOperateAuditType.WARNING);
                bizLogContext.setParams(userObj);//当前request请求参数
                bizLogContext.setDesc("通过接口快捷创建用户");
                logger.setUser(user);//当前操作人
                String mainSql = "select * from hrmresource where id=" + id;
                logger.setMainSql(mainSql, "id");//主表sql
                logger.setMainPrimarykey("id");//主日志表唯一key
                logger.setMainTargetNameColumn("lastname");//当前targetName对应的列（对应日志中的对象名）
                logger.before(bizLogContext);//写入操作前日志
                log.writeLog("process log 03-02...");
                String workstartdate = Util.null2String(userObj.get("workstartdate"));//参加工作日期
                String companystartdate = Util.null2String(userObj.get("companystartdate"));//入职日期
                String dsporder = Util.fromScreen3((String)userObj.get("dsporder"), 7);
                if (dsporder.length() == 0) dsporder = "" + id;
                if (accounttype.equals("0")) {

                    String encrptPassword = "" ;
                    String salt = "" ;
                    if(StringUtils.isNotBlank(password)){
                        String[] encrypts = PasswordUtil.encrypt(password);
                        encrptPassword = encrypts[0] ;
                        salt = encrypts[1] ;
                    }

                    sql = " update hrmresource set loginid='" + loginid + "', password='" + encrptPassword + "'," +
                            "seclevel=" + seclevel + ",dsporder=" + dsporder +
                            ",salt='" + salt + "',workstartdate='" + workstartdate + "',companystartdate='" + companystartdate + "' where id = " + id;
                } else {
                    sql = " update hrmresource set seclevel=" + seclevel + ",dsporder=" + dsporder +
                            " ,workstartdate='" + workstartdate + "',companystartdate='" + companystartdate + "' where id = " + id;
                }
                log.writeLog("process log 03-03...");

                if((workstartdate!=null && !"".equals(workstartdate)) || (companystartdate!=null && !"".equals(companystartdate))) {
                    try {
                        HrmResourceWorkService hrmResourceWorkService = new HrmResourceWorkService();
                        String workinfoid = String.valueOf(id);
                        HttpServletRequest tmpRequest = null;
                        tmpRequest.setAttribute("workstartdate", workstartdate);
                        tmpRequest.setAttribute("companystartdate", companystartdate);
                        hrmResourceWorkService.updateWorkInfo(tmpRequest, workinfoid, user);
                    }catch (Exception e){
                        log.writeLog(e);
                    }
                }
                log.writeLog("process log 03-04...");
                rs.executeSql(sql);
                try{
                    //登录信息签名
                    PasswordUtil.saveSign(""+id);
                }catch (Exception e){
                    log.writeLog(e);
                }
                log.writeLog("process log 03-05...");
                HrmFaceCheckManager.setUserPassowrd(id+"",password);
                HrmFaceCheckManager.sync(id+"",HrmFaceCheckManager.getOptUpdate(),"HrmResourceAddService_saveSimple_update",HrmFaceCheckManager.getOaResource());
                log.writeLog("process log 03-06...");
                LogUtil.writeBizLog(logger.getBizLogContexts());
            }

            retData.put("success", "1");
            retData.put("message", "success");
        } catch (Exception e) {
            log.writeLog("addSimpleUser Exception:"+ e);
            retData.put("success", "0");
            retData.put("message", "保存新建人员simple错误E01");
        }
        return retData;
    }

    /**
     * 创建用户base function
     * @param userObj
     * @return
     */
    public static Map<String, String> addResourceBase(JSONObject userObj, User user) {
        Map<String, String> retmap = new HashMap<String, String>();
        try {
            retmap.put("id", "0");

            LN LN = new LN();
            RecordSet rs = new RecordSet();
            DepartmentComInfo DepartmentComInfo = new DepartmentComInfo();
            ResourceComInfo ResourceComInfo = new ResourceComInfo();
            SalaryManager SalaryManager = new SalaryManager();
            ChgPasswdReminder reminder = new ChgPasswdReminder();
            RemindSettings settings = reminder.getRemindSettings();
            SysRemindWorkflow SysRemindWorkflow = new SysRemindWorkflow();
            CustomFieldTreeManager CustomFieldTreeManager = new CustomFieldTreeManager();
            DepartmentVirtualComInfo DepartmentVirtualComInfo = new DepartmentVirtualComInfo();

            String para = "";

//            FileUpload fu = new FileUpload(request);

            String id = Util.null2String(userObj.get("id"));
            String loginid = Util.null2String(userObj.get("loginid"));
            String workcode = Util.null2String(userObj.get("workcode")).trim();
            String lastname = Util.null2String(userObj.get("lastname")).trim();
            String sex = Util.null2String(userObj.get("sex")).trim();
            //暂时不支持图片

            String departmentid = Util.null2String(userObj.get("departmentid")).trim();

            String resourceimageid = "";
            String costcenterid = "";
            String joblevel = "";
            String jobactivitydesc = "";
            String managerid = "";
            String assistantid = "";
            String workroom = "";
            String telephone = "";
            String mobileshowtype = "";
            String mobilecall = "";
            String fax = "";
            String jobcall = "";
            String email = "";
            String dsporder = "";
            String systemlanguage = "7";
            String rcid = Util.null2String(userObj.get("rcId")).trim();//应聘人员id


//            String costcenterid = Util.null2String(userObj.get("costcenterid")).trim();
//            String joblevel = Util.null2String(userObj.get("joblevel")).trim();
//            String jobactivitydesc = Util.null2String(userObj.get("jobactivitydesc")).trim();
//            String managerid = Util.null2String(userObj.get("managerid")).trim();
//            String assistantid = Util.null2String(userObj.get("assistantid")).trim();
//            String workroom = Util.null2String(userObj.get("workroom")).trim();
//            String telephone = Util.null2String(userObj.get("telephone")).trim();
//            String mobileshowtype = Util.null2String(userObj.get("mobileshowtype")).trim();
//            String mobilecall = Util.null2String(userObj.get("mobilecall")).trim();
//            String fax = Util.null2String(userObj.get("fax")).trim();
//            String jobcall = Util.null2String(userObj.get("jobcall")).trim();
//            String email = Util.null2String(userObj.get("email")).trim();
//            String dsporder = Util.null2String(userObj.get("dsporder")).trim();
//            String systemlanguage = Util.null2String(userObj.get("systemlanguage")).trim();
//            String rcid = Util.null2String(userObj.get("rcId")).trim();//应聘人员id

            String jobtitle = Util.null2String(userObj.get("jobtitle")).trim();
            String status = Util.null2String(userObj.get("status")).trim();
            String locationid = Util.null2String(userObj.get("locationid")).trim();
            String mobile = Util.null2String(userObj.get("mobile")).trim();
            String accounttype = Util.null2String(userObj.get("accounttype")).trim();
            String belongto = Util.null2String(userObj.get("belongto")).trim();


            CheckItemBean mobileBean = new CheckItemBean("mobile", mobile, id);
            ValidateFieldManager.validate(mobileBean);
            if (!mobileBean.isPass()) {
                retmap.put("status", "-1");
                retmap.put("message", mobileBean.getCheckMsg());
                return retmap;
            }

//            CheckItemBean telephoneBean = new CheckItemBean("telephone", telephone, id);
//            ValidateFieldManager.validate(telephoneBean);
//            if (!telephoneBean.isPass()) {
//                retmap.put("status", "-1");
//                retmap.put("message", telephoneBean.getCheckMsg());
//                return retmap;
//            }
//            if (dsporder.length() == 0) dsporder = id;

            if (accounttype.equals("0")) {
                belongto = "-1";
            }

            String departmentvirtualids = Util.null2String(userObj.get("departmentvirtualids"));//虚拟部门id;

            rs.executeProc("HrmResourceMaxId_Get", "");
            rs.next();
            id = "" + rs.getInt(1);

//            if (!"".equals(rcid)) {
//                id = rcid;
//            }

            SimpleBizLogger logger = new SimpleBizLogger();

            BizLogContext bizLogContext = new BizLogContext();
            bizLogContext.setLogType(BizLogType.HRM);//模块类型
            bizLogContext.setBelongType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD);//所属大类型
            bizLogContext.setBelongTypeTargetName(SystemEnv.getHtmlLabelName(1361, user.getLanguage()));
            bizLogContext.setLogSmallType(BizLogSmallType4Hrm.HRM_RSOURCE_CARD_BASE);//当前小类型
            bizLogContext.setOperateType(BizLogOperateType.ADD);
            bizLogContext.setParams(userObj);//当前request请求参数
            logger.setUser(user);//当前操作人
            String cusFieldNames = ServiceUtil.getCusFieldNames("HrmCustomFieldByInfoType", -1, "b");
            String mainSql = "select a.*" + (cusFieldNames.length() > 0 ? "," + cusFieldNames : "") + " from hrmresource a left join cus_fielddata b on a.id=b.id and b.scope='HrmCustomFieldByInfoType' and b.scopeid=-1 where a.id=" + id;
            logger.setMainSql(mainSql, "id");//主表sql
            logger.setMainPrimarykey("id");//主日志表唯一key
            logger.setMainTargetNameColumn("lastname");//当前targetName对应的列（对应日志中的对象名）
            logger.before(bizLogContext);//写入操作前日志

            String managerstr = "";
            String seclevel = "";
            String sql = "";
//            String sql = "select managerstr, seclevel from HrmResource where id = " + Util.getIntValue(managerid);
//            rs.executeSql(sql);
//            while (rs.next()) {
//                String tmp_managerstr = rs.getString("managerstr");
//                /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr：8 begin***********/
//                if (!tmp_managerstr.startsWith(",")) tmp_managerstr = "," + tmp_managerstr;
//                if (!tmp_managerstr.endsWith(",")) tmp_managerstr = tmp_managerstr + ",";
//                /*********处理managerstr 不以逗号开始或者结束的情况 形如 managerstr：8 end ***********/
//                managerstr += tmp_managerstr;
//                managerstr = "," + managerid + managerstr;
//                managerstr = managerstr.endsWith(",") ? managerstr : (managerstr + ",");
//                seclevel = rs.getString("seclevel");
//            }

            String subcmpanyid1 = DepartmentComInfo.getSubcompanyid1(departmentid);
            RecordSet rst = new RecordSet();
            try {
                if(resourceimageid.length()==0)resourceimageid="null";
                if(costcenterid.length()==0)costcenterid="null";
                if(managerid.length()==0)managerid="null";
                if(assistantid.length()==0)assistantid="null";
                if(accounttype.length()==0)accounttype="null";
                if(belongto.length()==0)belongto="null";
                if(jobcall.length()==0)jobcall="null";
                if(mobileshowtype.length()==0)mobileshowtype="null";
                if(rst.getDBType().equalsIgnoreCase("postgresql"))
                {
                    if(joblevel.length()==0)joblevel=null;
                    if(dsporder.length()==0)dsporder=null;
                }
                workcode = CodeRuleManager.getCodeRuleManager().generateRuleCode(RuleCodeType.USER, subcmpanyid1, departmentid, jobtitle, workcode);
                para = "" + id + separator + workcode + separator + lastname + separator + sex + separator + resourceimageid + separator +
                        departmentid + separator + costcenterid + separator + jobtitle + separator + joblevel + separator + jobactivitydesc + separator +
                        managerid + separator + assistantid + separator + status + separator + locationid + separator + workroom + separator + telephone +
                        separator + mobile + separator + mobilecall + separator + fax + separator + jobcall + separator + subcmpanyid1 + separator + managerstr +
                        separator + accounttype + separator + belongto + separator + systemlanguage + separator + email + separator + dsporder + separator + mobileshowtype;
                try {
                    rst.executeProc("HrmResourceBasicInfo_Insert", para);
                }catch (Exception e) {
                    log.writeLog("HrmResourceBasicInfo_Insert run Exception0:"+ e.getMessage());
                    //由于加密处理在不同环境中可能会失败/抛异常，但并不影响数据创建，因此要做一下特殊判断
                    RecordSet rsCheck = new RecordSet();
                    String reCheckSql = "SELECT * FROM HrmResource WHERE id=? and loginid=?";
                    rsCheck.executeQuery(reCheckSql,id,loginid);
                    if(!rsCheck.next()){
                        log.writeLog("HrmResourceBasicInfo_Insert recheck 0:"+ e.getMessage());
                        retmap.put("status", "-1");
                        retmap.put("message", "HrmResourceBasicInfo_Insert run failed!");
                        return retmap;
                    }
                }
                if(Util.null2String(locationid).length()>0) {
                    rst.executeSql("update hrmresource set countryid=(select countryid from HrmLocations where id=" + locationid + "),"
                            + DbFunctionUtil.getInsertUpdateSetSql(rst.getDBType(), user.getUID()) + " where id=" + id);
                }
                String logidsql = "", quickSearchStr = new HrmCommonServiceImpl().generateQuickSearchStr(lastname);

                logidsql = "update HrmResource set loginid = ?, pinyinlastname = ?, ecology_pinyin_search = ? where id = ?";
                rst.executeUpdate(logidsql, loginid, quickSearchStr, quickSearchStr, id);

                if (seclevel == null || "".equals(seclevel)) {
                    seclevel = "0";
                }
            } catch (Exception e) {
                log.writeLog("HrmResourceBasicInfo_Insert run Exception1:"+ e.getMessage());
                e.printStackTrace();
                retmap.put("status", "-1");
                retmap.put("message", "HrmResourceBasicInfo_Insert run Exception!");
                return retmap;
            }

            boolean formdefined = false;
            weaver.system.CusFormSettingComInfo CusFormSettingComInfo = new weaver.system.CusFormSettingComInfo();
            weaver.system.CusFormSetting CusFormSetting = CusFormSettingComInfo.getCusFormSetting("hrm", "HrmResourceBase");
            if (CusFormSetting != null) {
                if (CusFormSetting.getStatus() == 2) {
                    //自定义布局页面
                    formdefined = true;
                }
            }
            int userid = user.getUID();
            String userpara = "" + userid + separator + today;
            para = "" + id;
            for (int i = 0; i < 5; i++) {
                int idx = i;
                if (formdefined) idx++;
                String datefield = Util.null2String(userObj.get("datefield" + idx));
                String numberfield = "" + Util.getDoubleValue((String)userObj.get("numberfield" + idx), 0);
                String textfield = Util.null2String(userObj.get("textfield" + idx));
                String tinyintfield = "" + Util.getIntValue((String)userObj.get("tinyintfield" + idx), 0);
                para += separator + datefield + separator + numberfield + separator + textfield + separator + tinyintfield;
            }
            rs.executeProc("HrmResourceDefine_Update", para);
            rs.executeProc("HrmResource_CreateInfo", "" + id + separator + userpara + separator + userpara);

            //用户自定义隐私设置
            UserPrivacyComInfo upc = new UserPrivacyComInfo();
            PrivacyComInfo pc = new PrivacyComInfo();
            Map<String, String> mapShowSets = pc.getMapShowSets();
            String insertSql = "";
            rs = new RecordSet();
            try {
                String deletePriSql = " delete from userprivacysetting where userid= '" + id + "'";
                rs.executeSql(deletePriSql);
                for (Map.Entry<String, String> me : mapShowSets.entrySet()) {
                    String fieldName = me.getKey();
                    String fieldVal = Util.null2String(mapShowSets.get(fieldName));
                    if (fieldVal.equals("1")) {
                        String tmpPK = id + "__" + fieldName;
                        String tmpPvalue = Util.null2String(userObj.get(fieldName + "showtype"));
                        insertSql = "insert into userprivacysetting (combinedid,userid,ptype,pvalue) values('" + tmpPK + "','" + id + "','" + fieldName + "','" + tmpPvalue + "')";
                        rs.executeSql(insertSql);
                    }
                }
                upc.removeUserPrivacyCache();
            } catch (Exception e) {
                log.writeLog("delete from userprivacysetting run Exception:"+ e.getMessage());
                e.printStackTrace();
            }

            // 改为只进行该人缓存信息的添加
            ResourceComInfo.addResourceInfoCache(id);
            SalaryManager.initResourceSalary(id);

            para = "" + id + separator + managerid + separator + departmentid + separator + subcmpanyid1 + separator + "0" + separator + managerstr;
            rs.executeProc("HrmResource_Trigger_Insert", para);

            String sql_1 = ("insert into HrmInfoStatus (itemid,hrmid) values(1," + id + ")");
            rs.executeSql(sql_1);
            String sql_2 = ("insert into HrmInfoStatus (itemid,hrmid) values(2," + id + ")");
            rs.executeSql(sql_2);
            String sql_3 = ("insert into HrmInfoStatus (itemid,hrmid) values(3," + id + ")");
            rs.executeSql(sql_3);
            String sql_10 = ("insert into HrmInfoStatus (itemid,hrmid) values(10," + id + ")");
            rs.executeSql(sql_10);

            String name = lastname;
            String CurrentUser = "" + user.getUID();
            String CurrentUserName = "" + user.getUsername();
            String SWFAccepter = "";
            String SWFTitle = "";
            String SWFRemark = "";
            String SWFSubmiter = "";
            String Subject = "";
            Subject = SystemEnv.getHtmlLabelName(15670, user.getLanguage());
            Subject += ":" + name;

            //modifier by lvyi 2013-12-31
            if (settings.getEntervalid().equals("1")) {//入职提醒
                String thesql = "select  hrmids from HrmInfoMaintenance where id<4 or id = 10";
                rs.executeSql(thesql);
                String members = "";
		    /*while(rs.next()){
				int hrmid_tmp = Util.getIntValue(rs.getString("hrmids"));//TD9392
				if(hrmid_tmp > 0 && user.getUID() != hrmid_tmp){
					members += ","+rs.getString("hrmids");
				}
		    }*/
                while (rs.next()) {
                    String hrmid_tmp = Util.null2String(rs.getString("hrmids"));//TD9392
                    if (hrmid_tmp.length() != 0) {
                        members += "," + rs.getString("hrmids");
                    }
                }
                if (!members.equals("")) {
                    members = members.substring(1);
                    members = duplicateRemoval(members, user.getUID() + "");
                    SWFAccepter = members;
                    SWFTitle = SystemEnv.getHtmlLabelName(15670, user.getLanguage());
                    SWFTitle += ":" + name;
                    SWFTitle += "-" + CurrentUserName;
                    SWFTitle += "-" + today;
//		        SWFRemark="<a href=/hrm/employee/EmployeeManage.jsp?hrmid="+id+">"+Util.fromScreen2(Subject,user.getLanguage())+"</a>";//支持E9弹窗
                    SWFRemark = "<a class='wea-hrm-new-employee-set'  onClick=\"openHrmNewEmployeeSetDialog(" + id + ")\"  style=\"cursor:pointer;\"  id = '" + id + "'>" + Util.fromScreen2(Subject, user.getLanguage()) + "</a>";
                    SWFSubmiter = CurrentUser;
                    SysRemindWorkflow.setPrjSysRemind(SWFTitle, 0, Util.getIntValue(SWFSubmiter), SWFAccepter, SWFRemark);
                }
            }

            //自动创建的用户暂时不处理自定义用户信息字段
            // CustomFieldTreeManager.editCustomDataE9Add("HrmCustomFieldByInfoType", -1, fu, Util.getIntValue(id, 0));

            //应聘人员的个人信息18条
            if (!"".equals(rcid)) {
                sql = "select * from HrmCareerApply where id = ?";
                rs.executeQuery(sql,id);
                if (rs.next()) {
                    String birthday = Util.null2String(rs.getString("birthday"));
                    String folk = Util.null2String(rs.getString("folk"));
                    String nativeplace = Util.null2String(rs.getString("nativeplace"));
                    String regresidentplace = Util.null2String(rs.getString("regresidentplace"));

                    String certificatenum = Util.null2String(rs.getString("certificatenum"));
                    String maritalstatus = Util.null2String(rs.getString("maritalstatus"));
                    String policy = Util.null2String(rs.getString("policy"));
                    String bememberdate = Util.null2String(rs.getString("bememberdate"));

                    String bepartydate = Util.null2String(rs.getString("bepartydate"));
                    String islabouunion = Util.null2String(rs.getString("islabouunion"));
                    String educationlevel = Util.null2String(rs.getString("educationlevel"));
                    String degree = Util.null2String(rs.getString("degree"));

                    String healthinfo = Util.null2String(rs.getString("healthinfo"));

                    String height = Util.null2String(rs.getString("height"));
                    if (height.indexOf(".") != -1) height = height.substring(0, height.indexOf("."));
                    String weight = Util.null2String(rs.getString("weight"));
                    if (weight.indexOf(".") != -1) weight = weight.substring(0, weight.indexOf("."));

                    String residentplace = Util.null2String(rs.getString("residentplace"));
                    String homeaddress = Util.null2String(rs.getString("homeaddress"));
                    String tempresidentnumber = Util.null2String(rs.getString("tempresidentnumber"));

                    para = "" + id + separator + birthday + separator + folk + separator + nativeplace + separator + regresidentplace + separator + maritalstatus + separator + policy + separator + bememberdate + separator + bepartydate + separator + islabouunion + separator + educationlevel + separator + degree + separator + healthinfo + separator + height + separator + weight + separator + residentplace + separator + homeaddress + separator + tempresidentnumber + separator + certificatenum;
                    RecordSet rs1 = new RecordSet();
                    rs1.executeProc("HrmResourcePersonalInfo_Insert", para);
                }
            }

            //更新虚拟组织部门id
            if (departmentvirtualids.length() > 0) {
                //保存前先删除需要删除的数据，因为有managerid 所以不能全部删除再保存
                sql = "delete from hrmresourcevirtual where resourceid=" + id + " and departmentid not in (" + departmentvirtualids + ")";
                rs.executeSql(sql);

                String[] departmentvirtualid = departmentvirtualids.split(",");
                for (int i = 0; departmentvirtualid != null && i < departmentvirtualid.length; i++) {
                    rs.executeSql(" select count(*) from HrmResourceVirtual where departmentid ='" + departmentvirtualid[i] + "' and resourceid = " + id);
                    if (rs.next()) {
                        //如果已存在 无需处理
                        if (rs.getInt(1) > 0) continue;
                    }

                    //写入
                    int tmpid = 0;
                    rs.executeSql("select max(id) from HrmResourceVirtual ");
                    if (rs.next()) {
                        tmpid = rs.getInt(1) + 1;
                    }
                    String subcompanyid = DepartmentVirtualComInfo.getSubcompanyid1(departmentvirtualid[i]);
                    sql = " insert into HrmResourceVirtual (id,resourceid,subcompanyid,departmentid ) " +
                            " values (" + tmpid + "," + id + "," + subcompanyid + "," + departmentvirtualid[i] + ")";
                    rs.executeSql(sql);
                }
            }

//            LogUtil.writeBizLog(logger.getBizLogContexts());
//            HrmFaceCheckManager.sync(id, HrmFaceCheckManager.getOptInsert(), "hrm_e9_HrmResourceBaseService_addResourceBase", HrmFaceCheckManager.getOaResource());

            //同步RTX端的用户信息.
            new OrganisationCom().checkUser(Util.getIntValue(id));
            new Thread(new OrganisationComRunnable("user", "add", "" + id)).start();
            ResourceComInfo.updateResourceInfoCache("" + id);
            new PluginUserCheck().clearPluginUserCache("messager");

            //OA与第三方接口单条数据同步方法开始
            new HrmServiceManager().SynInstantHrmResource("" + id, "1");
            //OA与第三方接口单条数据同步方法结束

            //新增人员实时同步到CoreMail邮件系统
            //CoreMailAPI.synUser(id);
            retmap.put("status", "1");
            retmap.put("id", id);
        } catch (Exception e) {
            log.writeLog("新建人员基本信息错误：" + e);
            retmap.put("status", "-1");
        }
        return retmap;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static String duplicateRemoval(String str, String userid) {
        String[] ss = str.split(",");
        List<String> list = new ArrayList<String>();
        for (String s : ss) {
            list.add(s.trim());
        }
        HashSet hs = new HashSet(list);
        list.clear();
        list.addAll(hs);
        if (list.contains(userid)) list.remove(userid);
        str = list.toString().replace("[", "").replace("]", "").replace(" ", "");
        return str;
    }

    /**
     * 按需update/insert 自定义用户字段表(Cus_FieldData)数据
     * @param map
     */
    public static void updateCusFieldData(Map<String, Object> map){
        String ecology_userid = Util.null2String(map.get("ecology_userid"));
        String yzy_userid = Util.null2String(map.get("yzy_userid"));
        String tyrz_userid = Util.null2String(map.get("tyrz_userid"));
        String yzy_position = Util.null2String(map.get("yzy_position"));
        String yzy_priority = Util.null2String(map.get("yzy_priority"));
        String yzy_status = Util.null2String(map.get("yzy_status"));

        //信息不足
        if("".equals(ecology_userid))
            return;
        if("".equals(yzy_userid) && "".equals(yzy_userid))
            return;

        String mixedId = "";
        if(!"".equals(tyrz_userid)) mixedId = tyrz_userid;
        if(!"".equals(yzy_userid)) mixedId = yzy_userid;

        boolean up_flag = false;
        String sql = "select * from Cus_FieldData where scope='HrmCustomFieldByInfoType' and scopeid='-1' and id='" + ecology_userid + "'";
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql);
        while (rs.next()) {
            RecordSet rs1 = new RecordSet();
            up_flag = true;
            String field0 = Util.null2String(map.get("field0"));
            String field3 = Util.null2String(map.get("field3"));
            String field7 = Util.null2String(map.get("field7"));
            String field8 = Util.null2String(map.get("field8"));
            String field9 = Util.null2String(map.get("field9"));

            String setStr = "";
            if(!"".equals(mixedId) && "".equals(field0)){
                setStr += ",field0='"+mixedId+"'";
            }
            if(!"".equals(mixedId) && "".equals(field3)){
                setStr += ",field3='"+mixedId+"'";
            }
            if(!"".equals(yzy_position) && "".equals(field7)){
                setStr += ",field7='"+yzy_position+"'";
            }
            if(!"".equals(yzy_priority) && "".equals(field7)){
                setStr += ",field8='"+yzy_priority+"'";
            }
            if(!"".equals(yzy_status) && "".equals(field7)){
                setStr += ",field9='"+yzy_status+"'";
            }
            if("".equals(setStr))
                //没有需要更新
                return;
            setStr = StringUtil.leftTrim(setStr);

            String updateUidSql = "update Cus_fieldData set " + setStr + " where scope='HrmCustomFieldByInfoType' and scopeid='-1' and id='" + ecology_userid + "'";
            log.writeLog("updateCusFieldData sql="+updateUidSql);
            rs1.executeUpdate(updateUidSql);
        }
        if (!up_flag) {
            String insertSql = "insert into cus_fielddata(seqorder,scope,scopeid,id,field0,field3,field7,field8,field9) values(1000,'HrmCustomFieldByInfoType',-1,?,?,?,?,?,?)";
            RecordSet rs2 = new RecordSet();
            log.writeLog("updateCusFieldData sql="+insertSql+"ecology_userid,mixedId,mixedId,yzy_position,yzy_priority,yzy_status");
            log.writeLog("bind params=["+ecology_userid+","+mixedId+","+mixedId+","+yzy_position+","+yzy_priority+","+yzy_status);
            rs2.executeUpdate(insertSql,ecology_userid,mixedId,mixedId,yzy_position,yzy_priority,yzy_status);
        }
    }
}